<?php
/**
 * Import Documents to initialise contact creation
 * 
 * @author Xavier VILAIN
 * @package Hive\Ressource
 * @license #license#
 */

use Fox\Html\Button\Help;
use Fox\Html\CheckBox;
use Fox\Html\DropList;
use Fox\Generator;
use Fox\Grid\FieldCat\Field\Renderer\Anchor;
use Fox\Dao\SqlFragment;
use Hive\Ressource\Document\Parser;
use Hive\Ressource;
use Fox\Html\Input\File;
use Fox\Html\Block;
use Fox\Html\Screen;

$xview = Xview::instance();
$screen = new Screen('sImport','import');
$screen->pageTitle(Msg(Hive::BUNDLE,Hive::TITLE_IMPORT_RESUME));
$block = new Block('bImport');

$customizing = Hive\Customizing::instance();

if($customizing->hasGroup()) {
	$groupingDp = $xview->component('ressource','grouping',array('authorizationCheck' => true));
	$block->add($groupingDp);
}
$sourcesDp = $xview->component('ressource','sources');
$block->add($sourcesDp);

$block->add(new File('filename',true,null,true))
		->excluded()
		->filter(Hive\Ressource\Document::$ALLOWED_EXTENSIONS)
		->label(Msg(Hive::BUNDLE,Hive::LABEL_PICK_RESUME));
// Options - Update Existing
$block->add(new CheckBox('updexisting',true))
		->add(new Help('updexistingHelp',Msg(Hive::BUNDLE,Hive::IMPORT_UPDATE_EXISITING_HELPER)));
$block->item('updexisting')->label(Msg(Hive::BUNDLE,Hive::IMPORT_UPDATE_EXISITING));
$block->labelSize(250,true);
$screen->add($block);

if($screen->submitted()) {
	
	if(isset($_FILES['filename']['name'])) {
		$fields = $screen->get();
		$language = $xview->language();
		$resultData = array();
		foreach($_FILES['filename']['name'] as $key => $fileName) {
			try {
				$tmp_name = $_FILES['filename']['tmp_name'][$key];
				$extension = pathinfo($fileName, PATHINFO_EXTENSION);
				if(!$block->item('filename')->checkExtension($extension)) {
					continue;
				}
				// Move File to the server
				$targetDir = _TEMP_;
				$time = $_SERVER['REQUEST_TIME'];	// add a time stamp in case of already existing file name
				$destination = $targetDir.$time.'-'.$fileName;
				if(move_uploaded_file($tmp_name,$destination))
				{
					// Create Document
					$document = new \Fox\Document();
					$dataFile['filename'] = $fileName;
					$dataFile['destination'] =  $targetDir;
					$dataFile['language'] = $language;
					$dataFile['doctype'] = Ressource::DOC_TYPE_DEFAULT;
					$dataFile['physicalname'] = $time.'-'.$fileName;
					$document->setFields($dataFile);
				}
				elseif(\Fox\Utilities\File::ERROR_EMPTY_FILE != $fileData['error']) //if(!empty($fileData['tmp_name']))
				{
					Fox\Message::Error("Error file {$fileName} has not been uploaded.<br>".\Fox\Utilities\File::handleErrors($fileData['error']));
					continue;
				}
				
				// Read Document Content
				$content = $document->content();
	
				// Extract email,first name and last name
				$data = null;
				$data = Parser::parse($content);
				if(!empty($data['email'])) {
					$data['email'] = trim($data['email']);
					// Check if ressource exist
					$finder = new Ressource();
					$res = $finder->find(new SqlFragment('email LIKE ?',array($data['email'].'%')),null,null,1);
					if(count($res) > 0) 
					{							
						if(count($res) == 1 && $fields['updexisting']) {
							$data = null;
							$ressource = $res[0];					
						} else {
							
							$resultData[] = array('filename' => $fileName,
												'email' => $data['email'],
												'rid' => $res[0]->getId(),
												'msg' => Msg(Hive::BUNDLE,
														Hive::ERR_EMAIL_ALREADY_EXIST));
							Fox\Message::Error(Msg(Hive::BUNDLE,
													Hive::ERR_EMAIL_ALREADY_EXIST_NO_IMPORT,
													$data['email'],$fileName
													));
	
							continue;
						}
					} else {
						$ressource = new Ressource();
						$data['grouping'] = $fields['grouping'];
						$data['creation_type'] = Ressource::CREATION_TYPE_RESUMES;
					}
					$document->create();
					// Create/Update Ressource
					$data['status'] = Ressource::STATUS_NEW;
					if(!empty($fields['source'])) {
						$data['source'] = $fields['source'];
					}
					$documentLink = new Ressource\Document();
					$documentLink->setFields(array('docid' => $document->getId()));
					$ressource->addToDocuments($documentLink);
					if($ressource->exists()) {
						
						$ressource->setFields($data);
						$ressource->prepareUpdate(Ressource::CHANGE_IMPORT);
						$ressource->update();
						$data['rid']  = $ressource->getId();
						$resultData[] = array('filename' => $fileName,
												'email' => $ressource->email,
												'rid' => $ressource->getId(),
												'msg' => Msg(Hive::BUNDLE,
														Hive::EXISTING_CONTACT_UPDATED));
						Fox\Message::Success(Msg(Fox\Msg::BUNDLE,Fox\Msg::MSG_UPDATE,$ressource->email));							
					} else {
						$ressource->setFields($data);
						$ressource->create();
						$data['rid'] = $ressource->getId();
						$data['filename'] = $fileName;
						$resultData[] = $data;
						Fox\Message::Success(Msg(Fox\Msg::BUNDLE,Fox\Msg::MSG_CREATE,$data['email']));
					}
					unset($ressource);
					$toBeIndexed[] = array('docid' => $document->getId(),'rid' => $data['rid']);
					
				} else {
					
					$resultData[] = array('filename' => $fileName,
												'email' => null,
												'msg' => Msg(Hive::BUNDLE,
														Hive::ERR_EMAIL_NOT_FOUND));
					Fox\Message::Error(Msg(Hive::BUNDLE,
												Hive::ERR_EMAIL_NOT_FOUND_IN,
												$fileName
												));
				}
			} catch (Fox\Object\Exception\Save $e) {

				Fox\Message::Error($e);
			}
		}
		$grid = new Fox\Grid('gResult');
		$grid->fieldcat(array('filename','email','first_name','last_name','phone1',
							array('message','msg')));
		$grid->fieldcat()->field('email')->renderers(new Anchor(
			Fox\Generator::url('ressource','main',null,array('rid' => Generator::useElement('rid'))),
			true
		));
		$grid->initialize($resultData);
	}
}
echo $screen->display();
if(isset($grid))
	echo $grid->display();
if(isset($toBeIndexed))
{
	$jsonData = json_encode($toBeIndexed);
	$jsonData = str_replace('"',"'",$jsonData);
?>
<script type="text/javascript">
<!--
$.ajax({
	type: "GET",
	url: "?mod=ressource&act=import&sac=indexing&xvtrs=none&jsonData=<?php echo $jsonData;?>",
	success: function(data)
	{
		$.fn.foxmessage(data.title);
	}	
});
//-->
</script>
<?php }?>